<?php
/**
 * CRM订单主表模型
 */
declare(strict_types=1);

namespace app\model\crm;

use app\model\BaseModel;

class Order extends BaseModel
{
    protected $name = 'crm_order';
    
    // 设置字段信息
    protected $schema = [
        'id'                      => 'int',
        'order_no'                => 'string',
        'customer_id'             => 'int',
        'customer_name'           => 'string',
        'customer_type'           => 'int',
        'id_number'               => 'string',
        'contact_id'              => 'int',
        'contact_name'            => 'string',
        'contact_phone'           => 'string',
        'order_category'          => 'int',
        'order_type'              => 'int',
        'related_order_id'        => 'int',
        'contract_no'             => 'string',
        'contract_amount'         => 'float',
        'post_amount'             => 'float',
        'total_amount'            => 'float',
        'paid_amount'             => 'float',
        'signer_id'               => 'int',
        'signer_name'             => 'string',
        'contract_start_date'     => 'int',
        'contract_end_date'       => 'int',
        'contract_sign_date'      => 'int',
        'contract_files'          => 'string',
        'payment_status'          => 'int',
        'contract_archive_status' => 'int',
        'approval_id'             => 'int',
        'approval_status'         => 'int',
        'delivery_status'         => 'int',
        'department_id'           => 'int',
        'remark'                  => 'string',
        'create_time'             => 'int',
        'update_time'             => 'int',
        'delete_time'             => 'int',
    ];
    
    // JSON字段
    protected $json = ['contract_files'];
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    // 软删除
    use \think\model\concern\SoftDelete;
    
    /**
     * 订单大类常量
     */
    const CATEGORY_LAWSUIT = 1;        // 诉讼订单
    const CATEGORY_LEGAL_SERVICE = 2;  // 非诉订单
    
    /**
     * 支付状态常量
     */
    const PAYMENT_STATUS_UNPAID = 0;     // 未支付
    const PAYMENT_STATUS_PARTIAL = 1;    // 部分支付
    const PAYMENT_STATUS_PAID = 2;       // 已支付
    
    /**
     * 审核状态常量
     */
    const APPROVAL_STATUS_PENDING = 0;    // 待审核
    const APPROVAL_STATUS_PROCESSING = 1; // 审核中
    const APPROVAL_STATUS_APPROVED = 2;   // 审核通过
    const APPROVAL_STATUS_REJECTED = 3;   // 审核拒绝
    
    /**
     * 交付状态常量
     */
    const DELIVERY_STATUS_PENDING = 0;     // 待交付
    const DELIVERY_STATUS_PROCESSING = 1;  // 交付中
    const DELIVERY_STATUS_COMPLETED = 2;   // 已完成
    
    /**
     * 关联客户信息
     */
    public function customer()
    {
        return $this->belongsTo(\app\model\crm\Customer::class, 'customer_id', 'id');
    }
    
    /**
     * 关联联系人
     */
    public function contact()
    {
        return $this->belongsTo(\app\model\crm\Contact::class, 'contact_id', 'id');
    }
    
    /**
     * 关联诉讼订单详情
     */
    public function lawsuitOrder()
    {
        return $this->hasOne(LawsuitOrder::class, 'order_id', 'id');
    }
    
    /**
     * 关联非诉订单详情
     */
    public function legalServiceOrder()
    {
        return $this->hasOne(LegalServiceOrder::class, 'order_id', 'id');
    }
    
    /**
     * 关联支付记录
     */
    public function payments()
    {
        return $this->hasMany(OrderPayment::class, 'order_id', 'id');
    }
    
    /**
     * 关联订单类型
     */
    public function orderType()
    {
        return $this->belongsTo(OrderType::class, 'order_type', 'id');
    }
    
    /**
     * 关联工作流审批
     */
    public function approval()
    {
        return $this->belongsTo(\app\model\workflow\WorkflowApproval::class, 'approval_id', 'id');
    }
    
    /**
     * 生成订单编号
     * 格式：ORD + 年月日 + 6位流水号
     */
    public static function generateOrderNo(): string
    {
        $prefix = 'ORD' . date('Ymd');
        
        // 获取今天最大的订单编号
        $lastOrder = self::where('order_no', 'like', $prefix . '%')
            ->order('order_no', 'desc')
            ->value('order_no');
        
        if ($lastOrder) {
            $lastNumber = (int)substr($lastOrder, -6);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . str_pad((string)$newNumber, 6, '0', STR_PAD_LEFT);
    }
    
    /**
     * 获取审核状态文本
     */
    public function getApprovalStatusTextAttr($value, $data): string
    {
        $statusMap = [
            self::APPROVAL_STATUS_PENDING    => '待审核',
            self::APPROVAL_STATUS_PROCESSING => '审核中',
            self::APPROVAL_STATUS_APPROVED   => '审核通过',
            self::APPROVAL_STATUS_REJECTED   => '审核拒绝',
        ];
        
        return $statusMap[$data['approval_status']] ?? '未知';
    }
    
    /**
     * 获取支付状态文本
     */
    public function getPaymentStatusTextAttr($value, $data): string
    {
        $statusMap = [
            self::PAYMENT_STATUS_UNPAID   => '未支付',
            self::PAYMENT_STATUS_PARTIAL  => '部分支付',
            self::PAYMENT_STATUS_PAID     => '已支付',
        ];
        
        return $statusMap[$data['payment_status']] ?? '未知';
    }
    
    /**
     * 获取交付状态文本
     */
    public function getDeliveryStatusTextAttr($value, $data): string
    {
        $statusMap = [
            self::DELIVERY_STATUS_PENDING     => '待交付',
            self::DELIVERY_STATUS_PROCESSING  => '交付中',
            self::DELIVERY_STATUS_COMPLETED   => '已完成',
        ];
        
        return $statusMap[$data['delivery_status']] ?? '未知';
    }
    
    /**
     * 获取合同归档状态文本
     */
    public function getContractArchiveStatusTextAttr($value, $data): string
    {
        $statusMap = [
            1 => '未签订',
            2 => '已签订',
            3 => '已归档'
        ];
        return $statusMap[$data['contract_archive_status']] ?? '未知';
    }
}